let express = require("express");
let router = express.Router();
let socket = require("./../socket");
const spawn = require('child_process').spawn;

function runTask(taskId) {
	const worker = spawn("node", ["bin/cli", "runtaskc", taskId, "--no-color"], {
		cwd: "/Users/jinliang/thin/fed-hbcloud-kit"
	});
	worker.stdout.on('data', (data) => {
		socket.add(data);
	});
	worker.stderr.on('data', (data) => {
		socket.add(data);
	});
	worker.on('close', (code) => {
		if (code === 0) {
			socket.done(true);
		} else {
			socket.done(false);
		}
	});
}

router.post("/run", (req, res) => {
	let taskId = req.body.taskid;
	if (taskId) {
		runTask(taskId);
		res.json({code: "1"});
	} else {
		res.json({code: "0"});
	}
});

module.exports = router;